package com.swufe.scoresforapp.FourMain;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.qlh.dropdownmenu.DropDownMenu;
import com.qlh.dropdownmenu.view.MultiMenusView;
import com.qlh.dropdownmenu.view.SingleMenuView;
import com.swufe.scoresforapp.R;
import com.swufe.scoresforapp.ScrollingMajorActivity;
import com.swufe.scoresforapp.ScrollingSchoolActivity;
import com.swufe.scoresforapp.Yonghu.Dataimport;
import com.swufe.scoresforapp.adapter.RecyclerAdapter;
import com.swufe.scoresforapp.bean.SchoolBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MajorFragment extends Fragment {

    private FragmentActivity instance;
    private String[] headers;//菜单头部选项
    private List<View> popupViews = new ArrayList<>();//菜单列表视图
    private DropDownMenu mDropDownMenu;
    private MultiMenusView multiMenusView;//多级菜单
    private SingleMenuView singleMenuView;//单级菜单
    //内容视图
    private View mView, contentView;

    public static final String CONTENT = "MajorFragment";
    private RecyclerAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<SchoolBean> mSchoolBeans;
    public static List<SchoolBean> saveSchoolBeans;
    private RecyclerView recyclerView;
    private View rootView;
    private Handler handler;
    private Context mContext;
    private String yonghu;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.activity_major_fragment, container, false);


        init();
        SharedPreferences preferences = getActivity().getSharedPreferences("Data", Context.MODE_PRIVATE);
        yonghu = preferences.getString("Name","");
        rootView = mView;
        recyclerView = (RecyclerView) rootView.findViewById(R.id.major_view);

        setmAdapter();
        initDatas();
        /*Button btn = view.findViewById(R.id.frag2_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "第二个Fragment", Toast.LENGTH_SHORT).show();
            }
        });*/
        return mView;
    }
    public void setmAdapter(){
        mContext =  this.getContext();
        mAdapter = new RecyclerAdapter(mContext, mSchoolBeans, "主专业");
        mAdapter.setOnDelListener(new RecyclerAdapter.onSwipeListener() {
            @Override
            public void onDel(int pos) {
                if (pos >= 0 && pos < mSchoolBeans.size()) {
                    Toast.makeText(getActivity(), "删除:" + pos, Toast.LENGTH_SHORT).show();
                    mSchoolBeans.remove(pos);
                    saveSchoolBeans.remove(pos);
                    mAdapter.notifyItemRemoved(pos);//推荐用这个
                    //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                    //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                    //mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onTop(int pos) {
                if (pos > 0 && pos < mSchoolBeans.size()) {
                    SchoolBean swipeBean = mSchoolBeans.get(pos);
                    mSchoolBeans.remove(swipeBean);
                    mAdapter.notifyItemInserted(0);
                    mSchoolBeans.add(0, swipeBean);
                    mAdapter.notifyItemRemoved(pos + 1);
                    if (mLayoutManager.findFirstVisibleItemPosition() == 0) {
                        recyclerView.scrollToPosition(0);
                    }
                    //notifyItemRangeChanged(0,holder.getAdapterPosition()+1);
                }
            }

            @Override
            public void onAdd(int pos, ImageView v) {

            }
        });
        mAdapter.setOnItemClickListener(new RecyclerAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int tag, View view, int position) {
                Toast.makeText(getContext(), "点击", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, ScrollingMajorActivity.class);
                intent.setClass(mContext, ScrollingMajorActivity.class);
                intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("information", new Gson().toJson(mSchoolBeans.get(position)));
                mContext.startActivity(intent);
            }

            @Override
            public void onItemLongClick(int tag, View view, int position) {
                Toast.makeText(mContext, "长按", Toast.LENGTH_SHORT).show();
            }
        });
        recyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        //流式
        //recyclerView.setLayoutManager(mLayoutManager = new GridLayoutManager(this.getContext(), 2));

        // 可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。我个人觉得意义不大，
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
                    if (null != viewCache) {
                        viewCache.smoothClose();
                    }
                }
                return false;
            }
        });
        mAdapter.notifyDataSetChanged();
    }
    public void setnewmAdapter(final RecyclerAdapter mAdapter,final List<SchoolBean> mSchoolBeans){
        mContext =  this.getContext();
        mAdapter.setOnDelListener(new RecyclerAdapter.onSwipeListener() {
            @Override
            public void onDel(int pos) {
                if (pos >= 0 && pos < mSchoolBeans.size()) {
                    Toast.makeText(getActivity(), "删除:" + pos, Toast.LENGTH_SHORT).show();
                    mSchoolBeans.remove(pos);
                    saveSchoolBeans.remove(pos);
                    mAdapter.notifyItemRemoved(pos);//推荐用这个
                    //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                    //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                    //mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onTop(int pos) {
                if (pos > 0 && pos < mSchoolBeans.size()) {
                    SchoolBean swipeBean = mSchoolBeans.get(pos);
                    mSchoolBeans.remove(swipeBean);
                    mAdapter.notifyItemInserted(0);
                    mSchoolBeans.add(0, swipeBean);
                    mAdapter.notifyItemRemoved(pos + 1);
                    if (mLayoutManager.findFirstVisibleItemPosition() == 0) {
                        recyclerView.scrollToPosition(0);
                    }
                    //notifyItemRangeChanged(0,holder.getAdapterPosition()+1);
                }
            }

            @Override
            public void onAdd(int pos, ImageView v) {

            }
        });
        mAdapter.setOnItemClickListener(new RecyclerAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int tag, View view, int position) {
                Toast.makeText(getContext(), "点击", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, ScrollingMajorActivity.class);
                intent.setClass(mContext, ScrollingMajorActivity.class);
                intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("information", new Gson().toJson(mSchoolBeans.get(position)));
                mContext.startActivity(intent);
            }

            @Override
            public void onItemLongClick(int tag, View view, int position) {
                Toast.makeText(mContext, "长按", Toast.LENGTH_SHORT).show();
            }
        });
        recyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        //流式
        //recyclerView.setLayoutManager(mLayoutManager = new GridLayoutManager(this.getContext(), 2));

        // 可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。我个人觉得意义不大，
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
                    if (null != viewCache) {
                        viewCache.smoothClose();
                    }
                }
                return false;
            }
        });
        mAdapter.notifyDataSetChanged();
    }
    private void initDatas() {
        mSchoolBeans = new ArrayList<>();
        saveSchoolBeans = new ArrayList<>();
        SharedPreferences preferences = this.getActivity().getSharedPreferences("Data", Context.MODE_PRIVATE);
        String yonghu = preferences.getString("Name","");
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==10){
                    saveSchoolBeans = mSchoolBeans;
                    setmAdapter();
                }
                super.handleMessage(msg);
            }
        };
        getYonghu(null);//初始化


    }


    //获取专业信息
    public void getYonghu(final String name){
        new Thread(new Runnable() { //开启线程

            public void run() {
                Dataimport in = new Dataimport();
                mSchoolBeans = in.getMajor(name,yonghu);
               // Log.i("CheckInfo",mSchoolBeans.get(0).Schoolname);
                Message msg = handler.obtainMessage(10);
                handler.sendMessage(msg);
            }
        }).start();
    }
    private void init() {
        instance = this.getActivity();
        initView();
        initMenus();
        initListener();

    }

    private void initView() {

        mDropDownMenu = (DropDownMenu) mView.findViewById(R.id.dropDownMenu);
    }

    private void initMenus() {

        popupViews.clear();
        headers = new String[]{"专业类别", "开设学校"};
        //初始化多级菜单
        final String[] levelOneMenu = {"医学类", "理学类", "文学类", "工学类"};
        final String[][] levelTwoMenu = {
                {"基础医学", "预防医学", "营养学", "临床医学", "麻醉学", "医学影像", "放射医学", "康复治疗学", "精神医学", "口腔医学", "口腔修复", "中医学"},
                {"数学与应用数学", "信息与计算科学", "数学基础科学", "物理学"},
                {"汉语言文学", "英语", "德语", "法语"},
                {"地质工程", "矿物资源学", "电子信息工程", "水利水电工程"}
        };
        if(getActivity()!=null){
            multiMenusView = new MultiMenusView(instance,levelOneMenu,levelTwoMenu);
            popupViews.add(multiMenusView);
            //初始化单级菜单
            String[] addressArrays = {"不限","北京大学", "上海交通大学", "复旦大学", "厦门大学", "武汉大学", "龙城大学"};
            singleMenuView = new SingleMenuView(instance,addressArrays);
            popupViews.add(singleMenuView);
            //初始化内容视图
            contentView = LayoutInflater.from(instance).inflate(R.layout.content_view,null);
            //装载
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers),popupViews,contentView);
        }


    }

    private void initListener() {

        //下拉菜单
        multiMenusView.setOnSelectListener(new MultiMenusView.OnSelectListener() {
            @Override
            public void getValue(String showText) {
                mDropDownMenu.setTabText(showText);
                mDropDownMenu.closeMenu();
            }
        });
        singleMenuView.setOnSelectListener(new SingleMenuView.OnSelectListener() {
            @Override
            public void getValue(int position, String showText) {
                mDropDownMenu.setTabText(showText);
                mDropDownMenu.closeMenu();
            }
        });
    }

}
